package com.wyiot.pet.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.wyiot.pet.model.dto.LoginDTO;
import com.wyiot.pet.model.vo.UserVO;
import com.wyiot.core.security.UserContext;
import com.wyiot.core.security.UserToken;
import com.wyiot.pet.service.LoginService;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 登录管理控制层
 *
 * @author yly
 * @since 2022/3/24
 */
@RestController
public class LoginController {
    @Resource
    LoginService loginService;

    /**
     * 登入
     *
     * @see LoginDTO
     */
    @PostMapping("/login/doLogin")
    public UserToken doLogin(@RequestBody @Validated LoginDTO loginDTO, BindingResult result) {


        UserVO user = loginService.checkLoginUser(loginDTO);
        StpUtil.login(user.getUserId());
        UserToken userToken = loginService.generateUserToken(user);
        UserContext.setToken(userToken);
        return userToken;
    }

    /**
     * 是否登入
     *
     */
    @RequestMapping("/login/isLogin")
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }


    /**
     * 查询token 信息
     *
     */
    @RequestMapping("/login/tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }


    /**
     * 注销
     *
     */
    @GetMapping("/login/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }


}